<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /**
       * @param {string[]} strs
       * @return {string}
       */
      var longestCommonPrefix = function (strs) {
        // 排个序提升效率
        strs.sort();
        // 最长的共同前缀肯定不会超过每个单词本身，找一个单词去跟所有单词匹配即可
        for (var i = 0; i < strs[0].length; i++) {
          // 拿到后面的几个单词遍历
          for (var j = 1; j < strs.length; j++) {
            // strs[j] 后面的单词
            if (strs[0][i] !== strs[j][i]) {
              return strs[0].slice(0, i);
            }
          }
        }
        return strs[0].slice(0, i);
      };

      var strs = ["flower", "flow", "flight"];
      console.log(longestCommonPrefix(strs));
    </script>
  </body>
</html>
